import { create } from "zustand";
import { UserService } from "@/services";
import { Profile } from "@/interfaces";

interface UserState {
  token: string | null;
  profile: Profile | null;
  setToken: (token: string | null) => void;
  setProfile: (data: Profile | null) => void;
  fetchProfile: () => Promise<Profile>;
}

const useUser = create<UserState>((set) => ({
  token: localStorage.getItem("token"),
  profile: null,
  setToken: (token) => {
    if (token) {
      localStorage.setItem("token", token);
    } else {
      localStorage.removeItem("token");
    }
    set({ token });
  },
  setProfile(data) {
    set({ profile: data });
  },
  fetchProfile: async () => {
    return new Promise((resolve, reject) => {
      UserService.profile()
        .then((data: any) => {
          set({ profile: data });
          resolve(data);
        })
        .catch(reject);
    });
  },
}));

export default useUser;

export function useProfile(): Partial<Profile> {
  return useUser((state) => state.profile || {});
}
